<template>
  <div
    class="projectDrawer-container"
    :class="[visible && isHide ? 'show' : 'hide']"
  >
    <div class="projectDrawer-body">
      <div class="header">
        项目列表
        <div class="close" @click="handleClose()">
          <icon-fonts icon="icon-zhankaishouqi"></icon-fonts>
        </div>
      </div>
      <div class="body">
        <div class="search-condition">
          <a-input-search
            v-model.trim="keyWord"
            @search="onSearch()"
            style="width: 100%"
            placeholder="请输入关键字"
          />
        </div>
        <div class="tree-container">
          <a-empty :image="simpleImage" v-if="threeData.length == 0" />
          <a-tree
            v-else
            :tree-data="threeData"
            :expanded-keys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            :selected-keys="selectedKeys"
            show-icon
            blockNode
            :replaceFields="{
              children: 'children',
              title: 'orgName',
              key: 'id',
            }"
            @expand="onExpand"
            @select="onSelect"
          >
            <!-- 自定义图标 -->
            <template slot="custom" slot-scope="{ expanded, children }">
              <a-icon
                :type="expanded ? 'folder-open' : 'folder'"
                theme="filled"
                v-if="children && children.length > 0"
              />
              <icon-fonts
                v-else
                class="project_space"
                icon="icon-xiangmu2"
              ></icon-fonts>
            </template>
          </a-tree>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { axios } from "@/utils/request";
import { Empty } from "ant-design-vue";
import cloneDeep from "lodash.clonedeep";
import { mapGetters } from "vuex";
import { addAttributeByKey, flatTreeData, _getUUID } from "@/utils/util.js";
export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      keyWord: "",
      //是否关闭
      isHide: false,
      //组织结构数据
      threeData: [],
      //当前选择的租户
      currentTenant: {},
      expandedKeys: [],
      selectedKeys: [],
      autoExpandParent: true,
      currenData: {},
    };
  },
  computed: {
    ...mapGetters(["systemName", "configData"]),
    systemName() {
      let index = this.configData.findIndex(
        (item) => item.code === "systemName"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "低代码开发平台";
      }
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.isHide = true;
        } else {
          this.isHide = false;
          this.handleClose();
        }
      },
      immediate: true,
    },
  },
  beforeCreate() {
    this.simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
  },
  mounted() {
    this.getTreeData();
  },
  methods: {
    //查询数据
    getTreeData() {
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/mdata/transformMdata/getTreeSysOrganizationByUserIdNotPro`,
            {},
            {
              headers: {
                "Content-Type": "application/json;charset=UTF-8",
              },
            }
          )
          .then((res) => {
            let { data } = res;
            this.cloneTreeData = cloneDeep(data ?? []);
            //格式化树形数据
            let dealData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              this.cloneTreeData,
              "children"
            );
            this.threeData = dealData;
            let flatData = flatTreeData(this.cloneTreeData, "children");
            this.expandedKeys = flatData.map((v) => v.id);
            this.currentTenant = flatData?.[0] ?? {};
            this.selectedKeys = [this.currentTenant?.id];
            this.$emit("changeSelect", this.currentTenant);
            resolve();
          })
          .catch((_) => {
            this.cloneTreeData = [];
            this.threeData = [];
            this.expandedKeys = [];
            this.selectedKeys = [];
            this.currentTenant = {};
            reject();
          });
      });
    },

    handleClose() {
      this.$emit("update:visible", false);
    },

    //树选择
    onSelect(_, { selected, node }) {
      let { dataRef } = node;
      this.selectedKeys = [dataRef.id];
      this.currentTenant = dataRef;
      this.$emit("changeSelect", this.currentTenant);
    },
    //树展开
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    onSearch() {
      let { keyWord, cloneTreeData } = this;
      let cloneData = cloneDeep(cloneTreeData);
      this.threeData = this.filterTree(cloneData, "children", (node) =>
        node.orgName.includes(keyWord)
      );
    },

    //过滤树形数据
    filterTree(data, children = "children", filterFunc) {
      return data
        .filter((node) => {
          // 如果当前节点符合条件，直接返回true
          if (filterFunc(node)) {
            return true;
          }
          // 如果当前节点有子节点，递归过滤子节点
          if (node[children]) {
            node[children] = this.filterTree(
              node[children],
              children,
              filterFunc
            );
            // 如果过滤后的子节点不为空，说明当前节点需要保留
            return node[children].length > 0;
          }
          // 当前节点不符合条件，也没有子节点或子节点不符合条件，返回false
          return false;
        })
        .map((node) => {
          // 创建新对象，避免修改原始数据
          return {
            ...node,
            [children]: node[children]
              ? this.filterTree(node[children], children, filterFunc)
              : [],
          };
        });
    },
  },
};
</script>

<style lang="less" scoped>
.projectDrawer-container {
  position: absolute;
  width: 296px;
  height: calc(100% - 16px);
  bottom: 16px;
  left: 10px;
  pointer-events: none;
  transition: 0.3s;
  background: #ffffff;
  z-index: 99;
  border-radius: 6px;
  &.hide {
    left: -100%;
  }
  .projectDrawer-body {
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    border-radius: 6px;
    pointer-events: all;
    .header {
      flex-shrink: 0;
      height: 56px;
      border-radius: 6px 6px 0px 0px;
      display: flex;
      align-items: center;
      box-sizing: border-box;
      padding: 0 16px;
      font-size: 16px;
      color: #333333;
      position: relative;
      border-bottom: 1px solid #d9d9d9;
      .close {
        width: 20px;
        height: 32px;
        position: absolute;
        background: #ffffff;
        top: 50%;
        transform: translateY(-50%);
        right: 0;
        border-radius: 4px 0px 0px 4px;
        border: 1px solid #dcdee2;
        border-right: 0;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        /deep/.anticon {
          color: #8c8c8c;
          font-size: 15px;
        }
      }
    }
    .body {
      flex: 1;
      background: #fff;
      padding: 0 0 10px 0;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      .search-condition {
        flex-shrink: 0;
        padding: 16px 16px 16px 16px;
        box-sizing: border-box;
        position: relative;
      }
      .tree-container {
        flex: 1;
        padding: 0 10px;
        overflow: auto;
        overflow-x: hidden;
        position: relative;
        /deep/.ant-tree {
          li {
            width: 100%;
            .ant-tree-node-content-wrapper {
              position: relative;
              width: calc(100% - 34px);
              padding: 0;
              .ant-tree-iconEle {
                font-size: 16px;
                .anticon-folder-open,
                .anticon-folder {
                  color: #ffb02c;
                }
                .project_space {
                  color: #555555;
                }
              }
              .ant-tree-title {
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
                display: inline-block;
                max-width: calc(100% - 40px);
                font-size: 14px;
                color: #333333;
              }
            }
          }
        }
        /deep/.ant-empty {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }
      }
    }
  }
}
</style>
